package com.situ.day15;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class Demo {

	@Test
	public void test1() throws ClassNotFoundException {
		// 1.  Class.forName(包名+类名)
		Class clazz1 = Class.forName("com.situ.day15.Student");
		// 2.   类名.class
		Class clazz2 = Student.class;
		// 3.  对象.getClass();
		Student student = new Student();
		Class clazz3 = student.getClass();
		
		System.out.println(clazz1 == clazz2);// true
		System.out.println(clazz2 == clazz3);// true
	}
	
	@Test
	public void testConstructor1() {
		Class clazz = Student.class;
		Constructor[] constructors = clazz.getDeclaredConstructors();
		for (Constructor constructor : constructors) {
			System.out.println(constructor);
			System.out.println(constructor.getName());// 返回构造方法的名字
			System.out.println(constructor.getModifiers());// public private
		}
	}
	
	@Test
	public void testConstructor2() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clazz = Student.class;
		// 得到指定参数的构造方法
		Constructor constructor = clazz.getDeclaredConstructor(String.class);
		System.out.println(constructor);
		// 加上之后就可以访问私有的构造方法
		constructor.setAccessible(true);
		// Student student = new Student("zhangsan");
		Student student = (Student) constructor.newInstance("zhangsan");
		System.out.println(student);
	}
	
	@Test
	public void testMethod() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//Student student = new Student();
		Class clazz = Class.forName("com.situ.day15.Student");
		Constructor constructor = clazz.getConstructor();
		Student student = (Student) constructor.newInstance();
		//student.setName("张三");
		Method method = clazz.getMethod("setName", String.class);
		method.invoke(student, "张三");
		System.out.println(student);
		
	}
}
